package com.wineryviewer.client;
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.event.MarkerClickHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.user.client.ui.SimplePanel;

public class MapPanel extends SimplePanel {
  private boolean mapInitialized = false;
  private boolean dataInitialized = false;
  private List<OfferMarker> offerMarkers = null;
  private List<JSONObject> offerDtos = null;
  private MapWidget map = null;
  
  public MapPanel() {
    Maps.loadMapsApi(
        "ABQIAAAAq3FviAq7L3FE7E3ittDbrBTcJZrV4pGHjdY3WXnmbqWpZMAWPhSwpz84tKvwDsZfQp2B9tNko1SHqA",
        "2", false, new Runnable() {
          public void run() { 
            LatLng healdsburg = LatLng.newInstance(38.62, -122.87);
            map = new MapWidget(healdsburg, 12);
            map.setSize("100%", "100%");
            map.addControl(new LargeMapControl()); 
            MapPanel.this.setWidget(map);
            if (dataInitialized) { initializeMarkers(); }
            mapInitialized = true;
          }
        }); 
  }
  
  private void initializeMarkers() {
    offerMarkers = new ArrayList<OfferMarker>();
    for (JSONObject dto : offerDtos) {
      OfferMarker marker = new OfferMarker(dto);
      offerMarkers.add(marker);
      marker.addMarkerClickHandler(new OfferMarkerClickHandler(map));
      map.addOverlay(marker);
    }
    this.setWidget(map);
  }
  
  private static class OfferMarkerClickHandler implements MarkerClickHandler {
    private MapWidget map;
    public OfferMarkerClickHandler(MapWidget map) { this.map = map; }
    
    public void onClick(MarkerClickEvent event) {
      OfferMarker offer = (OfferMarker) event.getSender();
      map.getInfoWindow().open(offer,
          new InfoWindowContent(offer.getInfoWindowWidget()));
    }
  }
  
  public void initializeData(JavaScriptObject foo) {
    offerDtos = new ArrayList<JSONObject>();
    JSONArray array = new JSONArray(foo);
    for (int i=0; i<=array.size()-1; i++) {
      offerDtos.add(array.get(i).isObject());
    }
    if (mapInitialized) { initializeMarkers(); }
    dataInitialized = true;    
  }
}

